package com.bbs.detai1713.controller;

import com.bbs.detai1713.model.RegisterInformation;
import com.bbs.detai1713.model.UpdateInformation;
import com.bbs.detai1713.service.DataService;
import com.bbs.detai1713.tool.ResultInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@Api(tags = "用户模块")
@Slf4j
@RestController
public class UserController {
    @Autowired
    DataService dataService;

    @RequestMapping("/isLogin")
    public ResultInfo isLogin() {
        return ResultInfo.success("已经登录了!");
    }

    @PostMapping("/login/success")
    public ResultInfo loginSuccess(@AuthenticationPrincipal UserDetails user) {

        return ResultInfo.success(dataService.loadUserByUsername(user.getUsername()), "登陆成功!");
    }

    @GetMapping("login/failure")
    public ResultInfo loginFailure() {
        return ResultInfo.autoResult(false, "登陆失败!");
    }

    @RequestMapping("/logout/success")
    public ResultInfo logoutSuccess() {
        return ResultInfo.autoResult(true, "注销成功!");
    }

    @PostMapping("/register")
    public ResultInfo register(@RequestBody RegisterInformation registerInformation) {
        log.info("注册用户信息,数据为:{}", registerInformation);
        if (dataService.register(registerInformation))
            return ResultInfo.autoResult(true, "注册成功!");
        else
            return ResultInfo.autoResult(false, "注册失败");
    }


    @PostMapping("/updateInformation")
    public ResultInfo updateInformation(@RequestBody UpdateInformation updateInformation, @AuthenticationPrincipal UserDetails userDetails) {

        log.info("更新用户信息,数据为:{}", updateInformation);
        try {
            dataService.updateInformation(updateInformation);
        } catch (Exception e) {
            return ResultInfo.failure("更新信息失败");

        }
        //更新用户信息
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities()));
        return ResultInfo.success("更新信息成功");

    }

//    @GetMapping("/selectInformation")
//    public ResultInfo selectInformation(Principal principal) {
//        log.info("查询用户信息,数据为:{}", principal);
//        return ResultInfo.success(principal, "查询成功");
//    }
}
